(function($) {
    $.fn.jCombo = function() {
        $(this).each(function() {
            var box = $("<div class='jComboBox'></div>");
            var tiRow = $("<div class='jComboRowInput'></div>");
            var selRow = $("<div class='jComboRowSelect'></div>");
            var textInput = $("<input type='text' class='jCombo'/>");
            var selectInput = $(this);
            selectInput.addClass('jCombo');

            function setSize() {
                box.width(selectInput.width());
                box.height(selectInput.height());
                textInput.width(selectInput.width() - 20);
                var hAdj = 2;
                if ($.browser.mozilla) hAdj = 1;
                textInput.height(selectInput.height() - hAdj);
            }
            setSize();
            selectInput.before(box);

            box.append(selRow);
            box.append(tiRow);
            tiRow.append(textInput);
            selRow.append(selectInput);

            var idx = selectInput.attr("selectedIndex");
            var txt = '';
            if (idx >= 0)
                txt = selectInput[0].options[idx].text
            if (txt == 'null') txt = '';
            textInput.val(txt);

            textInput[0].selectionStart = 0;
            textInput[0].selectionEnd = 0;


            selectInput.bind('focus', function() {
                tiRow.removeClass('hidden');
            });
            selectInput.bind('change', function() {
                var txt = selectInput[0].options[selectInput.attr("selectedIndex")].text
                if (txt == 'null') txt = '';
                textInput.val(txt);
                textInput.focus();
            });
            selectInput.bind('select', function() {
                var txt = selectInput[0].options[selectInput.attr("selectedIndex")].text
                if (txt == 'null') txt = '';
                textInput.val(txt);
                tInput.focus();
            });
            selectInput.children('option').bind('click', function() {
                var txt = selectInput[0].options[selectInput.attr("selectedIndex")].text
                if (txt == 'null') txt = '';
                textInput.val(txt);
                textInput.focus();
            });

            textInput.bind('keypress', function(e) {
                if (e.which == 13) {

                    var disp = textInput.val();
                    var val = textInput.val();

                    selectInput.append("<option value='" + val + "'>" + disp + "</option>");
                    selectInput.attr("selectedIndex", selectInput.children().length - 1);

                    specialOptValue()
                    setSize();
                    textInput.val('');
                    textInput.val(disp);
                    return false;
                }
            });

          
        });
    }
})(jQuery);
